package per.esmool;

import java.util.UUID;

import javax.servlet.http.HttpSession;

import com.jfinal.core.Controller;

public abstract class RedisCachedSessionController extends Controller {
		
	protected String redisSessionId = null;
	private RedisCachedSession session = null;
	
	public RedisCachedSessionController() {
		super();
	}
	
	public void loadSession() {
		HttpSession localSession = super.getSession();
		
		this.redisSessionId = this.getCookie(RedisCachedSession.REDIS_SESSION_DB_NAME);
		if (this.redisSessionId == null) {
			this.redisSessionId = UUID.randomUUID().toString();
			this.setCookie(RedisCachedSession.REDIS_SESSION_DB_NAME, this.redisSessionId, RedisCachedSession.SESSION_TIMEOUT);
		}
		
		this.session = new RedisCachedSession(RedisCachedSession.REDIS_SESSION_DB_NAME, this.redisSessionId, RedisCachedSession.SESSION_TIMEOUT, localSession);
	}
	
	public void saveSession() {
		this.session.save();
	}
	
	@Override
	public HttpSession getSession() {
		return this.session;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public <T> T getSessionAttr(String key) {
		T t = (T)this.session.getAttribute(key);
		return t;
	}
	
	@Override
	public Controller setSessionAttr(String key, Object value) {
		this.session.setAttribute(key, value);
		return this;
	}
	
	@Override
	public Controller removeSessionAttr(String key) {
		this.session.removeAttribute(key);
		return this;
	}

}
